package com.xiaode.controller.admin.happy;

import java.time.LocalDateTime;
import java.util.List;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaode.common.model.Chapter;
import com.xiaode.common.model.Curriculum;
import com.xiaode.common.model.CurriculumMod;
import com.xiaode.common.model.Division;
import com.xiaode.exce.EnumError;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

public class HappyCurriculumService {
	
	public Ret getCurriculumMod() throws Exception{
		List<CurriculumMod> cmList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE hierarchy = 0 ORDER BY num ASC ");
		for(CurriculumMod cm : cmList) {
			List<CurriculumMod> cmZList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE parent_id = ?", cm.getId());
			cm.put("cmZList", cmZList);
		}
		return Ret.ok("cmList", cmList);
	}
	
	public Ret moveCurriculumMod(Integer curriculumModId, Integer direction) throws Exception{
		CurriculumMod cm = CurriculumMod.dao.findById(curriculumModId);
		if(BeanUtil.isEmpty(cm)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_MOD_NULL.getObj());
		}
		int num = cm.getNum();
		if(direction == 1) {//上移
			CurriculumMod cm_s = CurriculumMod.dao.findFirst("SELECT * FROM curriculum_mod WHERE num = ?", num-1);
			if(BeanUtil.isNotEmpty(cm_s)) {
				cm_s.setNum(cm_s.getNum()+1);
				cm_s.update();
				cm.setNum(cm.getNum()-1);
				cm.update();
			}
		}else {
			CurriculumMod cm_s = CurriculumMod.dao.findFirst("SELECT * FROM curriculum_mod WHERE num = ?", num+1);
			if(BeanUtil.isNotEmpty(cm_s)) {
				cm_s.setNum(cm_s.getNum()-1);
				cm_s.update();
				cm.setNum(cm.getNum()+1);
				cm.update();
			}
		}
		return Ret.ok();
	}
	
	public Ret addCurriculumMod(Integer userId, String name, String icon, Integer parentId) throws Exception{
		CurriculumMod cm = new CurriculumMod();
		cm.setName(name);
		cm.setIcon(icon);
		cm.setCreatorId(userId);
		cm.setAddTime(LocalDateTime.now());
		if(parentId != null) {
			CurriculumMod pmd = CurriculumMod.dao.findById(parentId);
			if(BeanUtil.isNotEmpty(pmd)) {
				cm.setParentId(parentId);
				cm.setHierarchy(pmd.getHierarchy() + 1);
			}
		}
		cm.save();
		if(parentId == null) {
			Integer maxNum = Db.queryInt("SELECT MAX(num) FROM curriculum_mod ");
			cm.setNum(maxNum + 1);
			cm.update();
		}
		return Ret.ok("curriculumModId", cm.getId());
	}
	
	public Ret changeCurriculumMod(Integer userId, Integer curriculumModId, String name, String icon, Integer parentId) throws Exception{
		CurriculumMod cm = CurriculumMod.dao.findById(curriculumModId);
		if(BeanUtil.isEmpty(cm)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_MOD_NULL.getObj());
		}
		if(StrUtil.isNotBlank(name)) {
			cm.setName(name);
		}
		if(StrUtil.isNotBlank(icon)) {
			cm.setIcon(icon);
		}
		cm.setCreatorId(userId);
		if(parentId != null) {
			CurriculumMod pmd = CurriculumMod.dao.findById(parentId);
			if(BeanUtil.isNotEmpty(pmd)) {
				cm.setParentId(parentId);
				cm.setHierarchy(pmd.getHierarchy() + 1);
			}
		}
		cm.update();
		return Ret.ok();
	}
	
	@Before(Tx.class)
	public Ret deleCurriculumMod(Integer userId, Integer curriculumModId, Integer toCurriculumModId) throws Exception{
		CurriculumMod cm = CurriculumMod.dao.findById(curriculumModId);
		if(BeanUtil.isEmpty(cm)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_MOD_NULL.getObj());
		}
		if(toCurriculumModId != null) {//转移
			CurriculumMod tocm = CurriculumMod.dao.findById(toCurriculumModId);
			if(BeanUtil.isEmpty(tocm)) {
				return Ret.fail().set("error", EnumError.CURRICULUM_MOD_NULL.getObj());
			}
			Db.update("UPDATE curriculum_mod SET parent_id = ? WHERE parent_id = ?", toCurriculumModId, curriculumModId);
			cm.delete();
		}else {//全删
			List<Curriculum> curriculumList = Curriculum.dao.find("SELECT id FROM curriculum WHERE mod_id = ? ", curriculumModId);
			for(Curriculum curriculum : curriculumList) {
				deleCurriculum(userId, curriculum.getId());
			}
			cm.delete();
		}
		List<CurriculumMod> curriculumModList = CurriculumMod.dao.find("SELECT * FROM curriculum_mod WHERE num > ? ", cm.getNum());
		for(CurriculumMod curriculumMod : curriculumModList) {
			curriculumMod.setNum(curriculumMod.getNum()-1);
			curriculumMod.update();
		}
		return Ret.ok();
	}
	
	
	
	@Before(Tx.class)
	public Ret deleCurriculum(Integer userId, Integer curriculumId) throws Exception{
		Curriculum curriculum = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isNotEmpty(curriculum)){
			List<Chapter> cList = Chapter.dao.find("SELECT id FROM chapter WHERE curriculum_id = ?", curriculum.getId());
			for(Chapter c : cList) {
				List<Division> dList = Division.dao.find("SELECT id FROM division WHERE chapter_id = ?", c.getId());
				for(Division d : dList) {
					Db.delete("DELETE FROM division_file WHERE division_id = ?", d.getId());
					d.delete();
				}
				c.delete();
			}
			curriculum.delete();
		}
		return Ret.ok();
	}

	//（其中观看次数是课程下所有视频观看的次数）
	public Ret getCurriculumList(Integer userId, String lecturerName, String curriculumName, Integer curriculumId, Integer page, Integer limit) throws Exception{
		Kv kv = Kv.create().setIfNotBlank("curriculumName", curriculumName).setIfNotBlank("lecturerName", lecturerName).setIfNotNull("curriculumId", curriculumId);
		Page<Record> curriculumPage = Db.template("adminCurriculumList", kv).paginate(page, limit);
		for(Record c : curriculumPage.getList()) {
			List<Record> chapterList = Db.find("SELECT id,name FROM chapter WHERE curriculum_id = ?", c.getInt("id"));
			c.put("chapterList", chapterList);
			int viewSumZ = 0;
			for(Record chapter : chapterList) {
				List<Division> divisionList = Division.dao.find("SELECT id FROM division WHERE chapter_id = ?", chapter.getInt("id"));
				for(Division division : divisionList) {
					int viewNum = Db.queryInt("SELECT IFNULL(SUM(view_num), 0) sum FROM division_file WHERE division_id = ? AND is_video = 1", division.getId());
					viewSumZ = viewSumZ + viewNum;
				}
			}
			c.put("viewSumZ", viewSumZ);
		}
		return Ret.ok("curriculumPage", curriculumPage);
	}
	
	public Ret setPublic(Integer userId, Integer curriculumId) throws Exception{
		Curriculum c = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		c.setState(c.getState()==1?2:1);
//		c.setPublisherId(userId);
		c.setUpdateTime(LocalDateTime.now());
		c.update();
		return Ret.ok();
	}
	
	public Ret setGood(Integer userId, Integer curriculumId) throws Exception{
		Curriculum c = Curriculum.dao.findById(curriculumId);
		if(BeanUtil.isEmpty(c)) {
			return Ret.fail().set("error", EnumError.CURRICULUM_NULL.getObj());
		}
		Boolean isGood = c.getIsGood();
		if(!isGood) {
			Integer count = Db.queryInt("SELECT count(*) FROM curriculum WHERE is_good = 1");
			if(count >= 4) {
				return Ret.fail().set("error", EnumError.CURRICULUM_GOOD_COUNT.getObj());
			}
		}
		c.setIsGood(c.getIsGood()?false:true);
//		c.setPublisherId(userId);
		c.setUpdateTime(LocalDateTime.now());
		c.update();
		return Ret.ok();
	}
	
	public Ret getUserInteraction(Integer curriculumId, Integer page, Integer limit) throws Exception{
		Page<Record> ccPage = Db.paginate(page, limit, "SELECT * ", "FROM (SELECT DISTINCT create_account_id AS caid FROM curriculum_comment WHERE curriculum_id = ? AND user_type = 2) s", curriculumId);
		for(Record cc : ccPage.getList()) {
			Integer caid = cc.getInt("caid");
			String name = Db.queryStr("SELECT name FROM student WHERE accountId = ?", caid);
			int pl = Db.queryInt("SELECT COUNT(*) FROM curriculum_comment WHERE curriculum_id = ? AND create_account_id = ? AND stratum = ?", curriculumId, caid, 1);
			int hf = Db.queryInt("SELECT COUNT(*) FROM curriculum_comment WHERE curriculum_id = ? AND create_account_id = ? AND stratum = ?", curriculumId, caid, 2);
			cc.put("pl", pl);
			cc.put("hf", hf);
			cc.put("name", name);
		}
		return Ret.ok("ccPage", ccPage);
	}
	
}
